<?php
require_once "products/ProductVO.php";
require_once "products/CallingCardVO.php";
require_once "products/FlyerVO.php";
require_once "products/PosterVO.php";
require_once "products/LeafletVO.php";
require_once "products/EuroBookletVO.php";
require_once "products/CoverVO.php";
require_once "products/BlockVO.php";
require_once "products/InsetVO.php";
require_once "products/CaseVO.php";
require_once "products/TrioVO.php";
require_once "targets/TargetClass.php";
require_once "CalcOrderClass.php";

require_once "vos/CreateOrderResultVO.php";
require_once "vos/CalcCostOfOrderResultVO.php";

/**
* OrderClass 
*
* This class is designed to work with orders - 
* create, delete, eidt, get, etc.
*
* @author Victor Magarlamov <victor.magarlamov@gmail.com>
* @version 1.0
* @package presstrack
*/
 
class OrderClass 
{
	public $_explicitType = "presstrack.OrderClass";
    
	public $iOrderId;
	public $iLabel;
  	public $mCreationDate;
  	public $mExpiryDate;
  	public $iManagerId;	
  	public $mManagerName;
  	public $iCustomerId;
  	public $mCustomerName;
  	public $dPrice;
  	public $dDebt;
  	public $mNote;
  	public $mProductName;
  	public $iGroupNum;
  	public $arGroup;
  	public $iState;
  	public $iStatePaper;
	public $iStatePrepress;
	public $iStatePress;
	public $iStatePostpress;
	public $iStateDestination; 

	function __construct($idorder, $manager, $template) 
	{
		$this->iOrderId				= $idorder;
		$this->iManagerId			= $manager;
		$this->iCustomerId			= 0;
		$this->mCustomerName		= "?";
		$this->iLabel				= 0;
		$this->iGroupNum			= 0;
		$this->iState				= 1;
		$this->mCreationDate		= date("d/m/Y");
		$this->dPrice				= 0;
		$this->mProductName 		= "";
		$this->mStatePaper 			= 1;
		$this->mStatePrepress 		= 1;
		$this->mStatePress 			= 1;
		$this->mStatePostpress 		= 1;
		$this->mStateDestination	= 1;
		$this->arGroup 				= array();
			
		if (!empty($idorder))
		{
			$this->ReadFromDb($idorder);
		} 
		elseif (!empty($manager) && !empty($template)) 
		{
			$this->WriteToDb($template);
		}		
	}
	
	public function AddGroup($template) 
	{
		$this->iGroupNum = $this->iGroupNum + 1;
		$sql = sprintf("UPDATE press_track_new.order 
			SET group_num = %d WHERE idorder = %d", 
			$this->iGroupNum, $this->iOrderId);
		$query = mysql_query($sql);
		
		switch($template) {
			case "визитка":
				$product = new CallingCardVO();
				break;
			
			default:
			case "флаер":			
				$product = new FlyerVO();				
				break;
			
			case "плакат":			
				$product = new PosterVO();				
				break;
				
			case "лифлет": 			
				$product = new LeafletVO();				
				break;
				
			case "евробуклет":		
				$product = new EuroBookletVO();			
				break;
				
			case "журнал.обложка":	
				$product = new CoverVO("magazine");		
				break;
				
			case "журнал.блок":		
				$product = new BlockVO("magazine");		
				break;
				
			case "каталог обложка":	
				$product = new CoverVO("catalog");		
				break;
				
			case "каталог блок":	
				$product = new BlockVO("catalog");		
				break;
				
			case "газета блок":		
				$product = new BlockVO("newspaper"); 	
				break;
				
			case "газета вкладка":	
				$product = new InsetVO("newspaper"); 	
				break;
				
			case "книга обложка":	
				$product = new CoverVO("book"); 		
				break;
				
			case "книга блок":		
				$product = new BlockVO("book"); 		
				break;
				
			case "книга вкладка":		
				$product = new InsetVO("book"); 		
				break;
				
			case "папка-эконом":	
				$product = new CaseVO(); 		
				break;
				
			case "трио":
				$product = new TrioVO(); 		
				break;
		}
		
		foreach ($product->arOfProduct as $pr) 
		{
			$sql = sprintf("INSERT INTO product (product.group, product.order, "
				 . "product.label, product.run, product.size, product.color) "
				 . "VALUES (%d, %d, '%s', %d, '%s', '%s')", 
				 $this->iGroupNum, $this->iOrderId, 
				 $pr->label, $pr->run, $pr->size, $pr->color);
			$query 	= mysql_query($sql);		
			if (mysql_errno())
			{
				return mysql_errno() . ": " . mysql_error();
			}		
			$pr->idproduct	= mysql_insert_id();
		}
		
		foreach ($product->arOfTasks as $task) 
		{
			$sql = sprintf("INSERT INTO press_track_new.task 
				(task.label, task.value, task.section, task.state, task.order) 
				VALUES ('%s', '%s', %d, %d, %d)", 
				$task['label'], $task['value'], $task['section'], $task['state'], $this->iOrderId); 
			$query 	= mysql_query($sql);
			if (mysql_errno())
			{
				return mysql_errno() . ": " . mysql_error();
			}
			$idtask = mysql_insert_id();
			
			OrderClass::AddTarget($idtask);
			
			foreach ($product->arOfProduct as $pr) 
			{
				$sql = sprintf("INSERT INTO press_track_new.relation "
					 . "(relation.task_id, relation.product_id) VALUES (%d, %d)",  
					 $idtask, $pr->idproduct); 
				$query = mysql_query($sql);
			}
		}	
	}
	
	function RemoveGroup($index)
	{
		$sql = "SELECT task_id AS task_id FROM relation WHERE product_id IN "
			 . "(SELECT idproduct FROM press_track_new.product "
			 . "WHERE press_track_new.product.order = $this->iOrderId "  
			 . "AND press_track_new.product.group = $index)";
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();	
		}
		
		while ($task = mysql_fetch_object($query)) 
		{
			$sql = "DELETE FROM press_track_new.task "
				 . "WHERE press_track_new.task.idtask = $task->task_id";
			mysql_query($sql);
			if (mysql_errno())
			{
				return mysql_errno() . ": " . mysql_error();
			}		
		}
		
		$sql = "DELETE FROM press_track_new.product	"
			 . "WHERE press_track_new.product.order = $this->iOrderId " 
			 . "AND press_track_new.product.group = $index";
		mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}				
		
		if ($index < $this->iGroupNum)
		{
			for ($i = $index + 1; $i < $this->iGroupNum + 1; $i++)
			{
				$sql = "UPDATE product SET product.group = (product.group - 1) "
					 . "WHERE product.order = $this->iOrderId AND product.group = $i";
				mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}					
			}
		}	

		$this->iGroupNum--;
		$sql = sprintf("UPDATE press_track_new.order SET group_num = %d WHERE idorder = %d", 
			 $this->iGroupNum, $this->iOrderId);
		mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}		
		return "successful"; 
	}
	
	function WriteToDb($template)
	{
		$sql = sprintf("INSERT INTO press_track_new.order 
			(label, group_num, creation, state, manager) 
			VALUES (%d, %d, '%s', %d, %d)", 
			$this->iLabel, $this->iGroupNum, $this->mCreationDate, $this->iState, $this->iManagerId);
		$query = mysql_query($sql);
		$this->iOrderId = mysql_insert_id();
		
		switch ($template) {
			case 1:
				$this->AddGroup("визитка");
				break;
				
			default:
			case 2:
				$this->AddGroup("флаер");
				break;
				
			case 3:
				$this->AddGroup("плакат");
				break;
				
			case 4:
				$this->AddGroup("лифлет");
				break;
				
			case 5:
				$this->AddGroup("евробуклет");
				break;
				
			case 6: 
				$this->AddGroup("журнал.обложка");
				$this->AddGroup("журнал.блок");
				break;
				
			case 7: 
				$this->AddGroup("каталог обложка");
				$this->AddGroup("каталог блок");
				break;
				
			case 8: 
				$this->AddGroup("газета блок");
				$this->AddGroup("газета вкладка");
				break;
				
			case 9: 
				$this->AddGroup("книга обложка");
				$this->AddGroup("книга блок");
				$this->AddGroup("книга вкладка");
				break;
				
			case 10:
				$this->AddGroup("папка-эконом");
				break;
				
			case 11:
				$this->AddGroup("трио");
				break;
		}
	}
	
	function ReadFromDb($idorder)
	{
		set_time_limit(0);
		
		$sql = "SELECT press_track_new.order.label AS iLabel,
			press_track_new.order.group_num AS iGroupNum,
			press_track_new.order.creation AS mCreationDate,
			press_track_new.order.expiry AS mExpiryDate,
			press_track_new.order.state AS iState,
			press_track_new.order.note AS mNote,
			press_track_new.order.debt AS dDebt,
			press_track_new.order.manager AS iManagerId,
			press_track_new.order.customer AS iCustomerId,
			press_track_new.user.name AS mManagerName 
			FROM press_track_new.order, press_track_new.user 
			WHERE press_track_new.user.iduser = press_track_new.order.manager 
			AND press_track_new.order.idorder = $idorder LIMIT 1";
		$query = mysql_query($sql);		
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}		
		
		while ($order = mysql_fetch_object($query)) 
		{
			$this->iLabel			= $order->iLabel;
			$this->iGroupNum		= $order->iGroupNum;
			$this->mCreationDate	= $order->mCreationDate;
			$this->mExpiryDate		= $order->mExpiryDate;  
			$this->iState			= $order->iState;
			$this->mNote			= $order->mNote;
			$this->dDebt			= $order->dDebt;
			$this->iManagerId		= $order->iManagerId;	
			$this->mManagerName     = $order->mManagerName;
			if ((int)$order->iCustomerId > 0)
			{
				$this->iCustomerId	= $order->iCustomerId;
			}				
			
			$sql = "SELECT SUM(cost) AS total FROM task 
				WHERE task.order = $idorder";
			$query_cost = mysql_query($sql);
			
			while ($res = mysql_fetch_object($query_cost)) 
			{
				$this->dPrice = $res->total;
			}
			
			// собираем части заказа
			for ($g = 1; $g < $this->iGroupNum + 1; $g++) 
			{
				$part = $this->GetGroup($g);
								
				foreach ($part->products as $product)
				{
					$this->mProductName .= $product->label . ", " . $product->run . "\r";
				}
				
				$tsk_len	= count($part->tasks);
				$rel_len	= count($part->relations);
				$p_len		= count($part->products);
					
				for ($t_ind = 0; $t_ind < $tsk_len; $t_ind++) 
				{
					$temp = array();
					for($r_ind = 0; $r_ind < $rel_len; $r_ind++) 
					{
						if ($part->tasks[$t_ind]->idtask == $part->relations[$r_ind]->task_id) 
						{
							for ($p_ind = 0; $p_ind < $p_len; $p_ind++) 
							{
								if ($part->relations[$r_ind]->product_id == $part->products[$p_ind]->idproduct) 
								{
									$temp[] = $part->products[$p_ind]->label;
								}
							}
						}
					}
					if ($p_len == count($temp))
						$part->tasks[$t_ind]->product = "для всех изделий";
					else
						$part->tasks[$t_ind]->product = implode(';', $temp);
						
					switch ($part->tasks[$t_ind]->section) {
						case 2 : 
							if ($this->iStatePaper < $part->tasks[$t_ind]->state) 
								$this->iStatePaper = $part->tasks[$t_ind]->state; 
						break;
						
						case 3 : 
							if ($this->iStatePrepress < $part->tasks[$t_ind]->state) 
								$this->iStatePrepress = $part->tasks[$t_ind]->state; 
							break;
							
						case 4 : 
							if ($this->iStatePress < $part->tasks[$t_ind]->state) 
								$this->iStatePress = $part->tasks[$t_ind]->state; 
							break;
							
						case 5 : 
							if ($this->iStatePostpress < $part->tasks[$t_ind]->state) 
								$this->iStatePostpress = $part->tasks[$t_ind]->state; 
							break;
							
						case 6 : 
							if ($this->iStateDestination < $part->tasks[$t_ind]->state)
								$this->iStateDestination = $part->tasks[$t_ind]->state; 
							break;
					}
				}
				$this->arGroup[]	= clone $part;
			}				
			
			if ($this->iCustomerId != 0)
			{ 
				$sql = "SELECT press_track_new.user.name as customer 
					FROM press_track_new.user 
					WHERE press_track_new.user.iduser = $this->iCustomerId LIMIT 1";					
				$query4 = mysql_query($sql);							
				$cust = mysql_fetch_object($query4);
				$this->mCustomerName = $cust->customer;
			}
		}
	}
	
	function GetGroup($index)
	{
		$part->index = $index;
		
		$sql = "SELECT * FROM press_track_new.product 
			WHERE press_track_new.product.group = $index 
			AND press_track_new.product.order = $this->iOrderId";
		$query = mysql_query($sql);
		
		$part->tasks 		= array();
		$part->products 	= array();
		$part->relations 	= array();
		
		while ($product = mysql_fetch_object($query))
		{
			$part->products[] = $product;
			
			$sql = "SELECT * FROM relation 
				WHERE product_id = $product->idproduct";
			$query2 = mysql_query($sql);
			
			while ($rel = mysql_fetch_object($query2)) 
			{
				$part->relations[] = $rel;
				
				$sql = "SELECT * FROM press_track_new.task 
					WHERE idtask = $rel->task_id";
				$query3 = mysql_query($sql);
				
				while ($task = mysql_fetch_object($query3)) 
				{
					if (in_array($task, $part->tasks) == false ) 
					{
						$part->tasks[] = $task;	
					}
				}
			}
		}			
		return $part;			
	}
	
	static public function UpdateOrder($idorder, $param, $value)
	{
		switch ($param) {
			case "state":
				if ($value == '9')
				{
					$sql = sprintf("UPDATE press_track_new.task 
						SET state = 8 WHERE press_track_new.task.order = %d", 
						$idorder);
					$query = mysql_query($sql);
					if (mysql_errno())
					{
						return mysql_errno() . ": " . mysql_error() . " :1";
					}
				}			
				else if ($value == '1')
				{
					$sql = sprintf("UPDATE press_track_new.task 
						SET state = 1 WHERE press_track_new.task.order = %d", 
						$idorder);
					$query = mysql_query($sql);
					if (mysql_errno())
					{
						return mysql_errno() . ": " . mysql_error()  . " :2";
					}
				}
				
				$sql = sprintf("UPDATE press_track_new.order " 
					 . "SET %s = '%s' WHERE idorder = %d", 
					 $param, $value, $idorder);	
			break;
					
			case "debt":
				$sql = sprintf("UPDATE press_track_new.order 
					SET %s = %d WHERE idorder = %d", 
					$param, $value, $idorder);
				break;
				
			case "min_debt":
				$sql = sprintf("UPDATE press_track_new.order 
					SET debt = debt - %d WHERE idorder = %d", 
					$value, $idorder);					
				break;
			
			default:
				$sql = sprintf("UPDATE press_track_new.order " 
					 . "SET %s = '%s' WHERE idorder = %d", 
					 $param, $value, $idorder);			
		}
			
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error()  . " :3";
		}		
		return "successful";
	}
	
	static public function GenerateLabel()
	{
		$year = date('Y');
		$sql = "SELECT label, creation FROM press_track_new.order "
			 . "WHERE creation LIKE '%$year' ORDER BY label";
		$query = mysql_query($sql);
		if (mysql_errno()) 
		{ 
			return mysql_errno() . ": " . mysql_error();
		}
		
		$ar = array();
		while ($row = mysql_fetch_object($query))
		{
			$ar[] = $row->label;
		}
		$len = count($ar);
		for ($i=1; $i < $len + 1; $i++)
		{
			if (!in_array($i, $ar))
				break;
		}
		return $i;
	}
	
	static public function CalculateCost($idorder) 
	{
		$calc	= new CalcOrderClass();
		$result	= new CalcCostOfOrderResultVO();
		
		$sql = sprintf("SELECT idtask, label, value FROM press_track_new.task "
			 . "WHERE press_track_new.task.order = %d", $idorder);
		$query = mysql_query($sql);
		if (mysql_errno()) 
		{ 
			$result->mMessage = mysql_errno() . ": " . mysql_error();
			return $result;
		}		
		
		while ($task = mysql_fetch_object($query)) 
		{
			$calc->setCostFor($task);
		}
		
		$sql = sprintf("SELECT idtask, cost FROM press_track_new.task "
			 . "WHERE press_track_new.task.order = %d", $idorder);
		$query = mysql_query($sql);
		
		if (mysql_errno()) 
		{ 
			$result->mMessage = mysql_errno() . ": " . mysql_error();
			return $result;
		}
		
		while ($task = mysql_fetch_object($query)) 
		{
			$result->arTask[] = $task;
		}
		
		OrderClass::CalculateDebtForOrders();
		
		$result->bStatus = true;
		return $result;
	}
	
	static public function CalculateDebtForOrders()
	{
		$sql = "UPDATE press_track_new.order "
			 . "SET press_track_new.order.debt = "
			 . "(SELECT SUM(cost) FROM task WHERE task.order = idorder )";
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		
		$sql = "SELECT DISTINCT payment.order AS order_id FROM payment";
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		
		while ($pay = mysql_fetch_object($query)) 
		{
			$sql = sprintf("UPDATE press_track_new.order "
				 . "SET press_track_new.order.debt = "
				 . "debt - (SELECT SUM(sum) FROM payment WHERE payment.order = %d) "
				 . "WHERE idorder = %d", 
				 $pay->order_id, $pay->order_id);
			$query2 = mysql_query($sql);
			if (mysql_errno())
			{
				return mysql_errno() . ": " . mysql_error();
			}							
		}			
		return "successful";
	}
	
	static public function CopyOrder($idorder)
	{
		$src_order 		= new OrderClass($idorder, "", "");
		$creationResult	= new CreateOrderResultVO();
		
		$sql = sprintf("INSERT INTO press_track_new.order "
			 . "(label, creation, state, group_num, note, manager, customer) "
			 . "VALUES (%d, '%s', %d, %d, '%s', %d, %d)", 
			 0, date("d/m/Y"), 1, $src_order->iGroupNum, $src_order->mNote, 
			 $src_order->iManagerId, $src_order->iCustomerId);
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			$creationResult->message = mysql_errno() . ": " . mysql_error();
			return $creationResult;
		}		
		$id_of_copy = mysql_insert_id();
		
		foreach ($src_order->arGroup as $part) 
		{
			// copy products from source order
			foreach ($part->products as $product) 
			{
				$sql = sprintf("INSERT INTO press_track_new.product " 
					 . "(press_track_new.product.label, press_track_new.product.run, " 
					 . "press_track_new.product.size, press_track_new.product.color, " 
					 . "press_track_new.product.group, press_track_new.product.order) "
					 . "VALUES ('%s', %d, '%s', '%s', %d, %d)", 
					 $product->label, $product->run, 
					 $product->size, $product->color, 
					 $product->group, $id_of_copy);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
				$idproduct = mysql_insert_id();
			
				foreach ($part->relations as $rel) 
				{
					if($rel->product_id == $product->idproduct)
					{
						$rel->product_id = $idproduct;
					}
				}
			}

			// copy tasks from source order
			foreach ($part->tasks as $task) 
			{
				$sql = sprintf("INSERT INTO press_track_new.task "
					 . "(press_track_new.task.label, press_track_new.task.value, " 
					 . "press_track_new.task.section, press_track_new.task.execute, " 
					 . "press_track_new.task.cost, press_track_new.task.order) "
					 . "VALUES ('%s', '%s', %d, '%s', %d, %d)", 
					 $task->label, $task->value, 
					 $task->section, $task->execute, 
					 $task->cost, $id_of_copy);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
				$idtask = mysql_insert_id();
			
				foreach ($part->relations as $rel) 
				{
					if($rel->task_id == $task->idtask)
					{
						$rel->task_id = $idtask;
					}
				}						
			}
			
			foreach ($part->relations as $rel)
			{
				$sql = sprintf("INSERT INTO press_track_new.relation "
					 . "(product_id, task_id) VALUES (%d, %d)", 
					 $rel->product_id, $rel->task_id);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
			}
		}
		
		$creationResult->status	= true;
		$creationResult->order	= new OrderClass($id_of_copy, "", "");
		return $creationResult;
	}
	
	public static function AddProduct($idorder, $index_group, $label, $run, $size, $color)
	{
		$res->status = false;
		$sql = sprintf("INSERT INTO product (product.group, product.order, "
			 . "product.label, product.run, product.size, product.color) " 
			 . "VALUES (%d, %d, '%s', %d, '%s', '%s')", 
			 $index_group, $idorder, $label, $run, $size, $color);
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			$res->message = mysql_errno() . ": " . mysql_error();
			return $res;
		}		
		$res->idproduct = mysql_insert_id();
		$res->status = true;
		
		$sql = sprintf("SELECT DISTINCT task_id FROM relation WHERE product_id IN "
			 . "(SELECT DISTINCT idproduct FROM press_track_new.product "
			 . "WHERE press_track_new.product.group = %d "
			 . "AND press_track_new.product.order = %d)",
			 $index_group, $idorder);
		$query = mysql_query($sql);		
		while ($task = mysql_fetch_object($query)) 
		{
			OrderClass::AddRelation($res->idproduct, $task->task_id);
		}
		
		$sql = sprintf("SELECT * FROM relation WHERE  relation.product_id = %d", $res->idproduct);
		$query = mysql_query($sql);		
		while ($rel = mysql_fetch_object($query)) 
		{
			$res->relations[] = $rel;
		}		
		return $res;
	}
	
	static public function UpdateProduct($idproduct, $param, $value) 
	{
		switch ($param) {
			case "run":
				$sql = sprintf("UPDATE press_track_new.product SET run = %d WHERE idproduct = %d", $value, $idproduct);
			break;
			
			case "label":
			case "size":
			case "color":
				$sql = sprintf("UPDATE press_track_new.product SET %s = '%s' WHERE idproduct = %d", $param, $value, $idproduct);
			break;
		}

		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		else
		{
			return "successful";
		}
	}
	
	static public function RemoveProduct($idproduct) 
	{
		$sql = sprintf("DELETE FROM press_track_new.product WHERE idproduct = %d", $idproduct);
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		else
		{
			return "successful";
		}
	}
	
	static public function AddTask($idorder, $group, $label, $value, $section)
    {
		$res->status = false;
		$sql = sprintf("INSERT INTO press_track_new.task "
			 . "(press_track_new.task.label, press_track_new.task.value, "
			 . "press_track_new.task.section, press_track_new.task.order) " 
			 . "VALUES ('%s', '%s', %d, %d)", 
			 $label, $value, $section, $idorder); 
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			$res->message = mysql_errno() . ": " . mysql_error();
			return $res;
		}		
		$res->idtask = mysql_insert_id();
		$res->status = true;
		TargetClass::AddTarget($res->idtask);
		
		$sql = sprintf("SELECT DISTINCT product_id FROM relation "
			 . "WHERE product_id IN (SELECT DISTINCT idproduct "
			 . "FROM press_track_new.product "
			 . "WHERE  press_track_new.product.group = %d "
			 . "AND press_track_new.product.order = %d)",
			 $group, $idorder);
		$query = mysql_query($sql);		
		while ($product = mysql_fetch_object($query)) 
		{
			OrderClass::AddRelation($product->product_id, $res->idtask);
		}
		
		$sql = sprintf("SELECT * FROM relation WHERE  relation.task_id = %d", $res->idtask);
		$query = mysql_query($sql);		
		while ($rel = mysql_fetch_object($query)) 
		{
			$res->relations[] = $rel;
		}		
		return $res;
	}
	
	static public function UpdateTask($idtask, $param, $value)
	{
		switch ($param)
		{
			case "value":
				$sql = sprintf("UPDATE press_track_new.task SET value = '%s' "
					 . "WHERE idtask = %d", $value, $idtask);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
				$sql = sprintf("UPDATE press_track_new.task SET state = %d "
					 . "WHERE idtask = %d AND state != 1", 6, $idtask);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
				//$this->updateTargetLen($idtask);
			break;
		
			case "cost":
				$sql = sprintf("UPDATE press_track_new.task SET cost = %f "
					 . "WHERE idtask = %d", $value, $idtask);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
			
				// update debt
				$sql	= sprintf("SELECT * FROM task WHERE idtask = %d", $idtask);
				$query	= mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
				$task = mysql_fetch_object($query);
			
				$sql = sprintf("SELECT SUM(cost) as val FROM press_track_new.task "
					 . "WHERE press_track_new.task.order = %d", $task->order);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
				$order_price = mysql_fetch_object($query);
				
				$pay->val = 0;
				$sql = sprintf("SELECT SUM(sum) as val FROM payment "
					 . "WHERE payment.order = %d", $task->order);
				$query = mysql_query($sql);
				$pay = mysql_fetch_object($query);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
				$sql = sprintf("UPDATE press_track_new.order SET debt = %d "
					 . "WHERE idorder = %d", ($order_price->val - $pay->val), $task->order);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
			
				$sql = sprintf("UPDATE press_track_new.task SET state = %d "
					 . "WHERE idtask = %d AND state != 1", '6', $idtask);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
			break;
		
			case "state":
				$sql = sprintf("UPDATE press_track_new.task SET state = %d "
					 . "WHERE idtask = %d", $value, $idtask);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
			break;
		
			case "execute":
				$sql = sprintf("UPDATE press_track_new.task SET execute = '%s' "
					 . "WHERE idtask = %d", $value, $idtask);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
			break;
		
			case "state_note":
				$sql = sprintf("UPDATE press_track_new.task SET state_note = '%s' "
					 . "WHERE idtask = %d", $value, $idtask);
				$query = mysql_query($sql);
				if (mysql_errno())
				{
					return mysql_errno() . ": " . mysql_error();
				}
			break;
		}
		return "successful";
	}
	
	static public function RemoveTask($idtask) 
	{
		$sql = sprintf("DELETE FROM press_track_new.task WHERE idtask = %d", $idtask);
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		else
		{
			return "successful";
		}
	}
	
	static public function AddRelation($idproduct, $idtask)
    {
		$sql = sprintf("INSERT INTO relation (relation.task_id, relation.product_id) "
			 . "VALUES (%d, %d)", $idtask, $idproduct); 
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		else
		{
			return mysql_insert_id();
		}
	}
	
	static public function RemoveRelation($idrelation) 
	{
		$sql = sprintf("DELETE FROM press_track_new.relation "
			 . "WHERE idrelation = %d", $idrelation);
		$query = mysql_query($sql);
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}			
		else
		{
			return "successful";
		}
	}
	
	static public function AddPayment($idorder, $creation, $account, $sum, $note)
	{
		$sql = sprintf("INSERT INTO press_track_new.payment "
			 . "(payment.order, payment.creation, payment.account, " 
			 . "payment.sum, payment.note) VALUES (%d, '%s', '%s', %d, '%s')", 
			 $idorder, $creation, $account, $sum, $note);
		$query = mysql_query($sql);
		$idissue = mysql_insert_id();
		if (mysql_errno())
		{
			return mysql_errno() . ": " . mysql_error();
		}
		OrderClass::UpdateOrder($idorder, "min_debt", $sum);		
		return $idissue;
	}	
}
?>